package com.usian.behavior.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.behavior.mapper.ApUnlikesBehaviorMapper;
import com.usian.behavior.service.ApBehaviorEntryService;
import com.usian.behavior.service.ApUnlikesBehaviorService;
import com.usian.model.behavior.dtos.UnLikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApUnlikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
@Slf4j
@Service
public class ApUnlikesBehaviorServiceImpl extends ServiceImpl<ApUnlikesBehaviorMapper, ApUnlikesBehavior> implements ApUnlikesBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    ApUnlikesBehaviorMapper apUnlikesBehaviorMapper;

    @Override
    public ResponseResult unlike(UnLikesBehaviorDto dto) {
        //检查参数
        if (dto == null || dto.getArticleId() == null || (dto.getType()<0 && dto.getType()>1)){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询行为实体
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        if (apBehaviorEntry==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询是否有不喜欢记录
//        ApUnlikesBehavior one = getOne(Wrappers.<ApUnlikesBehavior>lambdaQuery().eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()).eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId()));
        ApUnlikesBehavior one = apUnlikesBehaviorMapper.findone(dto.getArticleId(), apBehaviorEntry.getEntryId());
        if (one == null && dto.getType()==0){
            //无则新增
            ApUnlikesBehavior apUnlikesBehavior = new ApUnlikesBehavior();
            apUnlikesBehavior.setArticleId(dto.getArticleId());
            apUnlikesBehavior.setType((int) dto.getType());
            apUnlikesBehavior.setCreatedTime(new Date());
            apUnlikesBehavior.setEntryId(apBehaviorEntry.getId());
            save(apUnlikesBehavior);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            //有则修改
            one.setType((int) dto.getType());
            updateById(one);
            return  ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }
}
